<template>
  <div class="order-detail-box">
    <s-header :name="'订单详情'" @callback="close"></s-header>
    <div class="order-status">
      <div class="status-item">
        <label>订单状态：</label>
        <span
        >{{ detail.orderStatusString
          }}<span v-if="detail.refundStatus === '已退款'" style="color: red"
          >(已退款)</span
          ><span
            v-else-if="detail.refundStatus === '退款中'"
            style="color: orange"
          >(退款中)</span
          ></span
        >
      </div>
      <div class="status-item">
        <label>订单编号：</label>
        <span>{{ detail.orderNo }}</span>
      </div>
      <div class="status-item">
        <label>下单时间：</label>
        <span>{{ detail.createTime }}</span>
      </div>

      <!-- 配送方式显示 -->
      <div class="status-item">
        <label>配送方式：</label>
        <span :class="deliveryTypeClass">
          {{ deliveryTypeText }}
        </span>
      </div>

      <!-- 开票状态显示 -->
      <div class="status-item" v-if="detail.isBill > 1">
        <label>发票状态：</label>
        <span :class="getBillStatusClass(detail.isBill)">
          {{ getBillStatusText(detail.isBill) }}
        </span>
      </div>

      <!-- 支付倒计时提示 -->
      <div v-if="detail.orderStatus == 0" class="payment-tip">
        <van-icon name="clock-o" color="#ff4444" />
        <span>30分钟内未付款，订单将自动取消</span>
      </div>

      <van-button
        v-if="detail.orderStatus == 0"
        style="margin-bottom: 10px"
        color="#1baeae"
        block
        @click="showPayFn"
      >去支付</van-button
      >

      <!-- 退款按钮 -->
      <van-button
        v-if="canApplyRefund"
        style="margin-bottom: 10px"
        color="#ff4444"
        block
        @click="showRefundDialog"
      >
        申请退款
      </van-button>

      <!-- 申请开票按钮 - 未开票时显示 -->
      <van-button
        v-if="detail.isBill == 1 && detail.orderStatus > 0"
        style="margin-bottom: 10px; margin-top: 10px"
        color="#ff976a"
        block
        @click="applyForInvoice"
      >
        申请开票
      </van-button>

      <!-- 开具发票按钮 - 只有当商家同意开票 (isBill=3) 且未开票时显示 -->
      <van-button
        v-if="detail.isBill == 3 && !detail.billUrl"
        style="margin-bottom: 10px; margin-top: 10px"
        color="#7232dd"
        block
        @click="showInvoiceDialog"
      >
        开具发票
      </van-button>

      <!-- 查看发票按钮 - 已开具发票时显示 -->
      <van-button
        v-if="detail.billUrl"
        style="margin-bottom: 10px; margin-top: 10px"
        color="#07c160"
        block
        @click="viewInvoice"
      >
        查看发票
      </van-button>
    </div>

    <!-- 价格信息区域 -->
    <div class="order-price">
      <div class="price-item">
        <label>商品金额：</label>
        <span>¥ {{ detail.goodsAmount }}</span>
      </div>

      <!-- 快递费显示 -->
      <div class="price-item" v-if="detail.deliveryFee && detail.deliveryFee > 0">
        <label>快递费：</label>
        <span>¥ {{ detail.deliveryFee }}</span>
      </div>

      <!-- 配送方式显示 -->
      <div class="price-item">
        <label>配送方式：</label>
        <span :class="deliveryTypeClass">
          {{ deliveryTypeText }}
        </span>
      </div>

      <!-- 自提地址显示 -->
      <div class="price-item" v-if="detail.deliveryType === 1 && detail.pickupAddress">
        <label>自提地址：</label>
        <span class="pickup-address">{{ detail.pickupAddress }}</span>
      </div>

      <!-- 收货地址显示 -->
      <div class="price-item" v-if="detail.deliveryType === 2 && detail.userAddress">
        <label>收货地址：</label>
        <span class="delivery-address">{{ detail.userAddress }}</span>
      </div>

      <div class="price-item total">
        <label>应付总额：</label>
        <span class="total-amount">¥ {{ detail.totalPrice }}</span>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <van-card
        v-for="(item, index) in detail.newBeeMallOrderItemVOS"
        :key="index"
        style="background: #fff; margin-bottom: 10px"
        :num="item.goodsCount"
        :price="item.sellingPrice"
        :desc="getProductDesc(item)"
        :title="getProductTitle(item)"
        @click="productDetail(item)"
        :thumb="prefix(item.goodsCoverImg)"
      >
        <!-- 自定义规格信息插槽 -->
        <template #tags>
          <div class="spec-tags" v-if="item.specText">
            <van-tag
              v-for="(spec, specIndex) in getSpecArray(item.specText)"
              :key="specIndex"
              type="primary"
              size="medium"
              class="spec-tag"
            >
              {{ spec }}
            </van-tag>
          </div>
        </template>

        <!-- 自定义底部插槽 -->
        <template #footer>
          <div class="product-footer" v-if="item.specText">
            <span class="spec-text">规格：{{ item.specText }}</span>
          </div>
        </template>
      </van-card>
    </div>

    <!-- 物流信息 - 只在快递方式且已发货时显示 -->
    <div v-if="detail.orderStatus == 3 && detail.deliveryType === 2" class="logistics-section">
      <!-- 物流信息内容保持不变 -->
      <div class="section-header" @click="toggleLogistics">
        <div class="section-title">
          <van-icon name="logistics" color="#1989fa" />
          <span>物流信息</span>
        </div>
        <div class="expand-icon">
          <van-icon :name="isLogisticsExpanded ? 'arrow-down' : 'arrow-up'" />
          <span>{{ isLogisticsExpanded ? "收起" : "展开" }}</span>
        </div>
      </div>

      <!-- 物流概览 -->
      <div class="logistics-overview">
        <div class="logistics-header">
          <span class="logistics-title">物流状态</span>
          <span v-if="logisticsData" class="logistics-no"
          >运单号：{{ logisticsData.mailNo }}</span
          >
          <span v-else class="logistics-no">加载中...</span>
        </div>
        <div v-if="logisticsData" class="logistics-status">
          <span class="current-status">{{ getLatestStatus() }}</span>
          <span class="update-time">{{ getLatestTime() }}</span>
        </div>
        <div v-else-if="logisticsLoading" class="logistics-status">
          <span>加载物流信息中...</span>
        </div>
        <div v-else-if="logisticsError" class="logistics-status error">
          <span>获取物流信息失败</span>
          <van-button size="mini" @click="getLogisticsInfo">重试</van-button>
        </div>
      </div>

      <!-- 物流时间轴 -->
      <div v-if="isLogisticsExpanded" class="logistics-content">
        <div v-if="logisticsData" class="logistics-timeline">
          <van-steps direction="vertical" :active="getActiveStep()">
            <van-step v-for="(route, index) in reversedRoutes" :key="index">
              <div class="route-item" :class="{ 'latest-route': index === 0 }">
                <div class="route-time">{{ formatTime(route.acceptTime) }}</div>
                <div class="route-status">{{ route.secondaryStatusName }}</div>
                <div class="route-address">{{ route.acceptAddress }}</div>
                <div class="route-remark">{{ route.remark }}</div>
              </div>
            </van-step>
          </van-steps>
        </div>

        <div
          v-if="!logisticsData && !logisticsLoading && logisticsError"
          class="no-logistics"
        >
          <van-empty description="暂无物流信息">
            <van-button
              round
              type="primary"
              class="bottom-button"
              @click="getLogisticsInfo"
            >
              重新加载
            </van-button>
          </van-empty>
        </div>
      </div>
    </div>

    <!-- 自提信息 - 只在自提方式时显示 -->
    <div v-if="detail.deliveryType === 1" class="pickup-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="shop-o" color="#07c160" />
          <span>自提信息</span>
        </div>
      </div>
      <div class="pickup-content">
        <div class="pickup-item">
          <van-icon name="location-o" color="#1989fa" />
          <div class="pickup-info">
            <div class="pickup-address-title">自提地址</div>
            <div class="pickup-address">{{ detail.pickupAddress || '未选择自提地址' }}</div>
          </div>
        </div>
        <div class="pickup-tips">
          <van-icon name="info-o" color="#ff976a" />
          <span>请在工作时间内到店自提，出示订单信息即可取货</span>
        </div>
      </div>
    </div>

    <!-- 开具发票弹窗 -->
    <van-dialog
      v-model="showInvoiceForm"
      title="开具发票"
      show-cancel-button
      :before-close="beforeInvoiceClose"
      @confirm="submitInvoice"
    >
      <div class="invoice-form">
        <van-form @submit="submitInvoice">
          <van-cell-group>
            <van-field
              v-model="invoiceForm.buyerName"
              label="购买方名称"
              placeholder="请输入购买方名称"
              required
              :rules="[{ required: true, message: '请输入购买方名称' }]"
            />
            <van-field
              v-model="invoiceForm.buyerTaxNum"
              label="纳税人识别号"
              placeholder="请输入纳税人识别号"
              required
              :rules="[{ required: true, message: '请输入纳税人识别号' }]"
            />
            <van-field
              v-model="invoiceForm.buyerAddress"
              label="购买方地址"
              placeholder="请输入购买方地址"
            />
            <van-field
              v-model="invoiceForm.buyerTel"
              label="购买方电话"
              placeholder="请输入购买方电话"
            />
            <van-field
              v-model="invoiceForm.buyerAccount"
              label="购买方账号"
              placeholder="请输入购买方账号"
            />
          </van-cell-group>
        </van-form>
      </div>
    </van-dialog>

    <!-- 退款申请弹窗 -->
    <van-dialog
      v-model="showRefundForm"
      title="申请退款"
      show-cancel-button
      @confirm="submitRefund"
    >
      <div class="refund-form">
        <van-form>
          <van-cell-group>
            <van-field
              v-model="refundForm.refundReason"
              label="退款原因"
              type="textarea"
              placeholder="请输入退款原因"
              rows="3"
              autosize
              required
              :rules="[{ required: true, message: '请输入退款原因' }]"
            />
            <van-field
              v-model="refundForm.refundAmount"
              label="退款金额"
              type="number"
              placeholder="请输入退款金额"
              required
              :rules="[{ required: true, message: '请输入退款金额' }]"
            >
              <template #extra>
                <span>元</span>
              </template>
            </van-field>
          </van-cell-group>
        </van-form>
      </div>
    </van-dialog>

    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>

    <van-popup v-model="showPay" position="bottom" :style="{ height: '24%' }">
      <div :style="{ width: '90%', margin: '0 auto', padding: '20px 0' }">
        <van-button color="#4fc08d" block @click="payOrder(detail.orderNo, 2)"
        >微信支付</van-button
        >
      </div>
    </van-popup>
    <nav-bar></nav-bar>
  </div>
</template>

<script>
import sHeader from "@/components/SimpleHeader";
import navBar from "@/components/NavBar";
import {
  getOrderDetail,
  cancelOrder,
  confirmOrder,
  payOrder,
  payWxOrder,
  getOrderLogistics,
  newBill,
  selectBill,
  applyRefund, // 新增退款申请接口
  applyInvoice, // 新增申请开票接口
} from "../service/order";
import { Dialog, Toast } from "vant";

export default {
  components: {
    navBar,
    sHeader,
  },
  data() {
    return {
      detail: {},
      showPay: false,
      logisticsData: null,
      logisticsLoading: false,
      logisticsError: false,
      isLogisticsExpanded: false,
      // 发票相关数据
      showInvoiceForm: false,
      invoiceForm: {
        orderNo: "",
        buyerName: "",
        buyerTaxNum: "",
        buyerAddress: "",
        buyerTel: "",
        buyerAccount: "",
      },
      isSubmittingInvoice: false,
      invoiceStatus: {
        isProcessing: false,
        lastOrderNo: "",
        billNo: "",
      },
      // 退款相关数据
      showRefundForm: false,
      refundForm: {
        orderNo: "",
        refundReason: "",
        refundAmount: 0,
      },
    };
  },
  computed: {
    reversedRoutes() {
      if (!this.logisticsData || !this.logisticsData.routes) {
        return [];
      }
      return this.logisticsData.routes.slice().reverse();
    },
    // 是否可以申请退款
    canApplyRefund() {
      // 订单状态为已支付(1)或已发货(2)且未申请过退款
      return (
        (this.detail.orderStatus === 1 || this.detail.orderStatus === 2) &&
        this.detail.refundStatus === "未退款"
      );
    },
    // 配送方式文本
    deliveryTypeText() {
      if (this.detail.deliveryType === 1) {
        return "自提";
      } else if (this.detail.deliveryType === 2) {
        return "快递配送";
      } else {
        return "未知";
      }
    },
    // 配送方式样式类
    deliveryTypeClass() {
      if (this.detail.deliveryType === 1) {
        return "delivery-type-pickup";
      } else if (this.detail.deliveryType === 2) {
        return "delivery-type-delivery";
      } else {
        return "";
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 获取开票状态文本 - 添加空值处理
    getBillStatusText(isBill) {
      // 处理空值情况
      if (isBill === null || isBill === undefined || isBill === "") {
        return "未开票";
      }
      switch (parseInt(isBill)) {
        case 1:
          return "未开票";
        case 2:
          return "开票申请中";
        case 3:
          return "商家同意开票";
        case 4:
          return "已开票";
        default:
          return "未开票";
      }
    },

    // 获取开票状态样式类 - 添加空值处理
    getBillStatusClass(isBill) {
      // 处理空值情况
      if (isBill === null || isBill === undefined || isBill === "") {
        return "";
      }
      switch (parseInt(isBill)) {
        case 2:
          return "bill-status-processing";
        case 3:
          return "bill-status-approved";
        case 4:
          return "bill-status-completed";
        default:
          return "";
      }
    },

    // 获取商品标题
    getProductTitle(item) {
      const title = item.goodsName || "";
      if (title.length > 20) {
        return title.substring(0, 20) + "...";
      }
      return title;
    },

    // 获取商品描述
    getProductDesc(item) {
      return "全场包邮";
    },

    // 将规格文本转换为数组
    getSpecArray(specText) {
      if (!specText) return [];
      return specText.split(";").filter((spec) => spec.trim());
    },

    // 格式化规格数据显示
    formatSpecData(specData) {
      if (!specData) return "";

      try {
        const specJson = JSON.parse(specData);
        const specText = [];

        for (const key in specJson) {
          if (
            specJson[key] &&
            specJson[key].attrName &&
            specJson[key].valueName
          ) {
            specText.push(
              `${specJson[key].attrName}: ${specJson[key].valueName}`
            );
          }
        }

        return specText.join("; ");
      } catch (error) {
        return specData;
      }
    },

    // 初始化
    async init() {
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      const { id } = this.$route.query;
      try {
        const { data } = await getOrderDetail(id);
        this.detail = data;

        // 处理规格数据显示
        if (this.detail.newBeeMallOrderItemVOS) {
          this.detail.newBeeMallOrderItemVOS.forEach((item) => {
            if (!item.specText && item.specData) {
              item.specText = this.formatSpecData(item.specData);
            }
          });
        }

        // 如果订单已经有发票链接，重置开票状态
        if (this.detail.billUrl) {
          this.resetInvoiceStatus();
        }

        // 如果订单状态是已发货且是快递方式，获取物流信息
        if (this.detail.orderStatus == 3 && this.detail.deliveryType === 2) {
          await this.getLogisticsInfo();
        }

        Toast.clear();
      } catch (error) {
        Toast.clear();
        Toast("加载订单详情失败");
      }
    },

    // 申请开票 - 将 isBill 状态从 1 改为 2
    async applyForInvoice() {
      Dialog.confirm({
        title: "申请开票",
        message: "确认要向商家申请开具发票吗？",
      })
        .then(async () => {
          Toast.loading({
            message: "提交申请中...",
            forbidClick: true,
          });

          try {
            const result = await applyInvoice({ orderNo: this.detail.orderNo });
            if (result.resultCode === 200) {
              Toast.success("开票申请提交成功，等待商家审核");
              // 刷新订单详情
              await this.init();
            } else {
              Toast.fail(result.message || "申请开票失败");
            }
          } catch (error) {
            Toast.fail("申请开票失败，请稍后重试");
          }
        })
        .catch(() => {
          // 用户取消
        });
    },

    // 显示退款申请弹窗
    showRefundDialog() {
      this.refundForm = {
        orderNo: this.detail.orderNo,
        refundReason: "",
        refundStatus: "用户申请退款",
        refundAmount: this.detail.totalPrice || 0,
      };
      this.showRefundForm = true;
    },

    // 提交退款申请
    async submitRefund() {
      if (!this.refundForm.refundReason.trim()) {
        Toast.fail("请输入退款原因");
        return;
      }

      if (!this.refundForm.refundAmount || this.refundForm.refundAmount <= 0) {
        Toast.fail("请输入有效的退款金额");
        return;
      }

      Toast.loading({
        message: "提交退款申请中...",
        forbidClick: true,
      });

      try {
        const result = await applyRefund(this.refundForm);
        if (result.resultCode === 200) {
          Toast.success("退款申请提交成功");
          this.showRefundForm = false;
          // 刷新订单详情
          await this.init();
        } else {
          Toast.fail(result.message || "退款申请提交失败");
        }
      } catch (error) {
        Toast.fail("提交退款申请失败，请稍后重试");
      }
    },

    // 显示开具发票弹窗
    showInvoiceDialog() {
      // 检查是否已经有正在处理的发票
      if (
        this.invoiceStatus.isProcessing &&
        this.invoiceStatus.lastOrderNo === this.detail.orderNo
      ) {
        // 直接调用查询开票结果接口，不显示弹窗
        this.queryInvoiceResult();
        return;
      }

      // 正常显示弹窗
      this.invoiceForm = {
        orderNo: this.detail.orderNo,
        buyerName: "企业名称/个人",
        buyerTaxNum: "339901999999198",
        buyerAddress: "杭州市",
        buyerTel: "0571-88888888",
        buyerAccount: "中国工商银行 111111111111",
      };
      this.showInvoiceForm = true;
    },

    // 查询开票结果
    async queryInvoiceResult() {
      if (this.isSubmittingInvoice) {
        return;
      }

      this.isSubmittingInvoice = true;
      Toast.loading({
        message: "正在查询发票开具状态...",
        forbidClick: true,
        duration: 0,
      });

      try {
        const result = await selectBill(this.detail.orderNo);

        if (result.resultCode === 200) {
          // 查询成功，更新订单详情
          await this.init();

          // 自动下载发票
          if (result.message) {
            this.downloadInvoice(result.message);
            Toast.success("发票开具成功！");
          } else {
            Toast.success("发票查询完成");
          }

          // 重置开票状态
          this.resetInvoiceStatus();
        } else {
          Toast.fail(result.message || "查询发票失败");
        }
      } catch (error) {
        Toast.fail("查询发票失败，请稍后重试");
      } finally {
        this.isSubmittingInvoice = false;
      }
    },

    // 自动查询开票结果
    async autoQueryInvoiceResult() {
      if (!this.invoiceStatus.isProcessing) {
        return;
      }

      Toast.loading({
        message: "自动查询开票结果...",
        forbidClick: true,
        duration: 0,
      });

      try {
        const result = await selectBill(this.detail.orderNo);

        if (result.resultCode === 200) {
          if (result.message) {
            // 开票成功，有发票链接
            Toast.success("发票开具成功！");

            // 更新订单详情
            await this.init();

            // 自动下载发票
            this.downloadInvoice(result.message);

            // 重置开票状态
            this.resetInvoiceStatus();
          } else {
            // 仍在处理中，继续等待
            Toast.success("发票仍在处理中，请耐心等待...");

            // 5秒后再次查询
            setTimeout(() => {
              this.autoQueryInvoiceResult();
            }, 5000);
          }
        } else {
          // 查询失败，提示用户手动查询
          Toast.fail("查询开票结果失败，请稍后手动查询");
        }
      } catch (error) {
        // 查询出错，10秒后重试
        setTimeout(() => {
          this.autoQueryInvoiceResult();
        }, 10000);
      }
    },

    // 提交发票申请
    async submitInvoice() {
      if (this.isSubmittingInvoice) {
        return;
      }

      this.isSubmittingInvoice = true;
      Toast.loading({
        message: "正在开具发票...",
        forbidClick: true,
        duration: 0,
      });

      try {
        const result = await newBill(this.invoiceForm);

        if (result.resultCode === 200) {
          if ("发票开具中，请稍后再试" === result.message) {
            // 记录开票处理状态
            this.invoiceStatus.isProcessing = true;
            this.invoiceStatus.lastOrderNo = this.detail.orderNo;
            this.invoiceStatus.billNo = result.data || "";

            Toast.loading({
              message: "发票开具中，请等待",
              forbidClick: false,
              duration: 4000,
            });

            this.showInvoiceForm = false;
            // 3秒后自动查询开票结果
            setTimeout(() => {
              this.autoQueryInvoiceResult();
            }, 3000);
          } else {
            // 开票成功
            Toast.success("发票开具成功！");
            this.showInvoiceForm = false;

            // 更新订单详情，显示发票链接
            await this.init();

            // 自动下载发票
            if (result.message) {
              this.downloadInvoice(result.message);
            }

            // 重置开票状态
            this.resetInvoiceStatus();
          }
        } else {
          Toast.fail(result.message || "发票开具失败");
        }
      } catch (error) {
        Toast.fail("开具发票失败，请稍后重试");
      } finally {
        this.isSubmittingInvoice = false;
      }
    },

    // 重置发票状态
    resetInvoiceStatus() {
      this.invoiceStatus = {
        isProcessing: false,
        lastOrderNo: "",
        billNo: "",
      };
    },

    // 下载发票
    downloadInvoice(billUrl) {
      if (!billUrl) {
        Toast.fail("发票链接无效");
        return;
      }

      // 创建隐藏的下载链接
      const link = document.createElement("a");
      link.href = billUrl;
      link.target = "_blank";
      link.download = `发票_${this.detail.orderNo}.pdf`;

      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      Toast.success("发票下载中...");
    },

    // 查看发票
    viewInvoice() {
      if (this.detail.billUrl) {
        window.open(this.detail.billUrl, "_blank");
      } else {
        Toast.fail("发票链接无效");
      }
    },

    // 发票弹窗关闭前的确认
    beforeInvoiceClose(action, done) {
      if (action === "cancel") {
        if (this.isSubmittingInvoice) {
          Toast("正在开具发票，请稍候...");
          return false;
        }
      }
      done();
    },

    // 其他原有方法保持不变
    toggleLogistics() {
      this.isLogisticsExpanded = !this.isLogisticsExpanded;
    },

    async getLogisticsInfo() {
      if (!this.detail.orderNo) return;

      this.logisticsLoading = true;
      this.logisticsError = false;

      try {
        const response = await getOrderLogistics(this.detail.orderNo);
        if (response.message === "SUCCESS") {
          if (
            response.data.msgData &&
            response.data.msgData.routeResps &&
            response.data.msgData.routeResps.length > 0
          ) {
            this.logisticsData = response.data.msgData.routeResps[0];
            this.isLogisticsExpanded = true;
          } else {
            this.logisticsError = true;
            Toast("暂无物流信息");
          }
        } else {
          this.logisticsError = true;
          Toast(response.errorMsg || "获取物流信息失败");
        }
      } catch (error) {
        this.logisticsError = true;
        Toast("获取物流信息失败，请稍后重试");
      } finally {
        this.logisticsLoading = false;
      }
    },

    getLatestStatus() {
      if (!this.logisticsData || !this.logisticsData.routes.length)
        return "暂无状态信息";
      const latestRoute =
        this.logisticsData.routes[this.logisticsData.routes.length - 1];
      return latestRoute.secondaryStatusName;
    },

    getLatestTime() {
      if (!this.logisticsData || !this.logisticsData.routes.length) return "";
      const latestRoute =
        this.logisticsData.routes[this.logisticsData.routes.length - 1];
      return this.formatTime(latestRoute.acceptTime);
    },

    formatTime(timeStr) {
      if (!timeStr) return "";
      const date = new Date(timeStr);
      const now = new Date();
      const isToday = date.toDateString() === now.toDateString();

      if (isToday) {
        return `今天 ${timeStr.split(" ")[1]}`;
      } else {
        return timeStr;
      }
    },

    getActiveStep() {
      if (!this.logisticsData) return 0;

      const routes = this.logisticsData.routes;
      let activeIndex = 0;

      for (let i = 0; i < routes.length; i++) {
        if (routes[i].secondaryStatusCode === "401") {
          activeIndex = routes.length - 1 - i;
          break;
        } else if (routes[i].secondaryStatusCode === "301") {
          activeIndex = routes.length - 1 - i;
          break;
        }
      }

      return activeIndex;
    },

    productDetail(item) {
      this.$router.push({ path: `product/${item.goodsId}` });
    },

    cancelOrder(id) {
      Dialog.confirm({
        title: "确认取消订单？",
      })
        .then(() => {
          cancelOrder(id).then((res) => {
            if (res.resultCode == 200) {
              Toast("删除成功");
              this.init();
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },

    confirmOrder(id) {
      Dialog.confirm({
        title: "是否确认订单？",
      })
        .then(() => {
          confirmOrder(id).then((res) => {
            if (res.resultCode == 200) {
              Toast("确认成功");
              this.init();
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },

    showPayFn() {
      this.showPay = true;
    },

    async payOrder(id, type) {
      Toast.loading;
      await payWxOrder({ orderNo: id, payType: type });
      this.showPay = false;
      this.init();
    },

    close() {
      Dialog.close();
    },
  },
};
</script>

<style lang="less" scoped>
.order-detail-box {
  background: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 50px;
  box-sizing: border-box;

  .order-status {
    background: #fff;
    margin-top: 44px;
    padding: 20px;
    font-size: 15px;
    .status-item {
      margin-bottom: 10px;
      label {
        color: #999;
      }
      span {
      }
    }
  }

  .order-price {
    background: #fff;
    margin: 20px 0;
    padding: 20px;
    font-size: 15px;
    .price-item {
      margin-bottom: 10px;
      label {
        color: #999;
      }
      span {
      }

      &.total {
        border-top: 1px solid #f0f0f0;
        padding-top: 10px;
        margin-top: 10px;
        .total-amount {
          font-size: 18px;
          font-weight: bold;
          color: #ee0a24;
        }
      }
    }

    .pickup-address,
    .delivery-address {
      color: #1989fa;
      font-weight: 500;
    }
  }

  // 配送方式样式
  .delivery-type-pickup {
    color: #07c160;
    font-weight: bold;
  }

  .delivery-type-delivery {
    color: #1989fa;
    font-weight: bold;
  }

  // 自提信息区域
  .pickup-section {
    background: #fff;
    margin: 20px 0;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;

      .section-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: bold;

        .van-icon {
          margin-right: 8px;
          color: #07c160;
        }
      }
    }

    .pickup-content {
      padding: 15px 20px;

      .pickup-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 15px;

        .van-icon {
          margin-right: 10px;
          margin-top: 2px;
          color: #1989fa;
        }

        .pickup-info {
          flex: 1;

          .pickup-address-title {
            font-weight: bold;
            margin-bottom: 5px;
            color: #333;
          }

          .pickup-address {
            color: #666;
            line-height: 1.4;
          }
        }
      }

      .pickup-tips {
        display: flex;
        align-items: flex-start;
        background: #fff9f0;
        border-radius: 4px;
        padding: 10px;
        font-size: 13px;
        color: #ff976a;

        .van-icon {
          margin-right: 8px;
          margin-top: 1px;
          flex-shrink: 0;
        }
      }
    }
  }

  .product-list {
    margin-bottom: 20px;

    .van-card {
      margin-top: 0;
    }

    .spec-tags {
      margin-top: 8px;

      .spec-tag {
        margin-right: 6px;
        margin-bottom: 4px;
        background: #f0f8ff;
        color: #1989fa;
        border: 1px solid #d1ebff;
      }
    }

    .product-footer {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #f5f5f5;

      .spec-text {
        font-size: 12px;
        color: #666;
        background: #f8f9fa;
        padding: 2px 6px;
        border-radius: 3px;
      }
    }
  }

  .payment-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff9f9;
    border: 1px solid #ffdddd;
    border-radius: 4px;
    padding: 10px;
    margin: 15px 0;
    color: #ff4444;
    font-size: 14px;
  }

  // 发票状态样式
  .bill-status-processing {
    color: #ff976a; // 处理中 - 橙色
  }

  .bill-status-approved {
    color: #1989fa; // 已同意 - 蓝色
  }

  .bill-status-completed {
    color: #07c160; // 已完成 - 绿色
  }

  // 发票表单样式
  .invoice-form {
    padding: 20px;

    .van-field {
      margin-bottom: 12px;
    }
  }

  // 退款表单样式
  .refund-form {
    padding: 20px;

    .van-field {
      margin-bottom: 12px;
    }
  }

  // 物流信息区域样式
  .logistics-section {
    background: #fff;
    margin: 20px 0;
    overflow: visible;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;

      .section-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: bold;

        .van-icon {
          margin-right: 8px;
          color: #1989fa;
        }
      }

      .expand-icon {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #666;

        .van-icon {
          margin-left: 4px;
          transition: transform 0.3s;
        }
      }

      &:active {
        background-color: #f8f9fa;
      }
    }

    .logistics-overview {
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;

      .logistics-header {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        .logistics-title {
          font-weight: bold;
          margin-right: 10px;
          color: #333;
        }

        .logistics-no {
          font-size: 12px;
          color: #666;
          margin-left: auto;
        }
      }

      .logistics-status {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .current-status {
          font-size: 16px;
          font-weight: bold;
          color: #f01616;
        }

        .update-time {
          font-size: 12px;
          color: #999;
        }

        &.error {
          color: #ee0a24;
          justify-content: space-between;
        }
      }
    }

    .logistics-timeline {
      padding: 15px 20px;
      max-height: none;
      overflow: visible;

      .route-item {
        padding: 8px 0;

        .route-time {
          font-size: 14px;
          color: #333;
          font-weight: 500;
          margin-bottom: 4px;
        }

        .route-status {
          font-size: 16px;
          color: #07c160;
          font-weight: bold;
          margin-bottom: 4px;
        }

        .route-address {
          font-size: 13px;
          color: #666;
          margin-bottom: 4px;
        }

        .route-remark {
          font-size: 13px;
          color: #999;
          line-height: 1.4;
        }

        &.latest-route {
          .route-time {
            color: #f01616;
            font-weight: bold;
          }
          .route-status {
            color: #f01616;
          }
        }
      }
    }

    .no-logistics {
      padding: 30px 0;
    }
  }

  .bottom-safe-area {
    height: 20px;
  }

  .van-card__content {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>
